package cn.alise.controller.admin;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.alise.controller.common.BaseController;
import cn.alise.qdp.model.common.RoleTree;
import cn.alise.qdp.model.menu.Menu;
import cn.alise.qdp.model.role.Role;
import cn.alise.qdp.model.role.RoleMenu;
import cn.alise.qdp.model.user.UserRole;
import cn.alise.qdp.service.admin.MenuService;
import cn.alise.qdp.service.admin.RoleMenuService;
import cn.alise.qdp.service.admin.RoleService;
import cn.alise.qdp.service.user.UserRoleService;
import cn.alise.util.JSONResult;

import com.alibaba.fastjson.JSONArray;


/**
 * 角色管理控制器
 */
@Controller
@RequestMapping(value = "/role")
public class RoleController extends BaseController {

	private static final long serialVersionUID = 3071751434812887748L;
	private static final String ERROR_TITLE = "_error";
	private static final String REDIRECT_LIST = "redirect:list";

	@Resource(name = "roleService")
	private RoleService roleService;
	
	@Resource(name = "roleMenuService")
	private RoleMenuService roleMenuService;
	
	@Resource(name = "userRoleService")
	private UserRoleService userRoleService;
	
	@Resource(name = "menuService")
	private MenuService menuService;

	/**
	 * 角色列表
	 */
	@RequestMapping(value = "/list")
	public String list(HttpServletRequest request, Model model,
			Role role) {
		
		List<Role> roleList = this.roleService.list(role);
		
		model.addAttribute("list", roleList);

		return "pages/role/role-list";
	}
	
	/**
	 * 跳转到角色创建页面
	 */
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(HttpServletRequest request, Model model) {
		
		return "pages/role/role-new";
	}
	
	/**
	 * ajax角色同名检测
	 */
	@RequestMapping(value = "/sameCheckRoleName", method = RequestMethod.POST)
	public void sameCheckRoleName(HttpServletRequest request, HttpServletResponse response) {
		
		String roleName = request.getParameter("roleName");
		Role role = new Role();
		role.setRoleName(roleName);
		
		//ajax检测同名角色名称
		if(roleName!=null && !"".equals(roleName)) {
			
			JSONResult result = new JSONResult();
			List<Role> check = this.roleService.list(role);
			
			if(check.size()>0) {
				result.setStatus(1);
				result.setMessage("1");
				this.getPrintWriter(response, new JSONResult(1,new Object(),"已有相同的角色名称!"));
			} else {
				result.setStatus(0);
				result.setMessage("0");
				this.getPrintWriter(response, new JSONResult(0,new Object(),"没有相同名称!"));
			}
		}
	}
	
	/**
	 * 新增角色
	 */
	@RequestMapping(value = "/insert", method = RequestMethod.POST)
	public String insert(HttpServletRequest request, Role role, RedirectAttributes attr) {
		
		//session 获取userId
		Long userId = this.getAccountFromSession().getUserId();
		
		if(role.getOrderNo()!=null && !"".equals(role.getOrderNo())) {
			role.setOrderNo(role.getOrderNo());//序列
		} else {
			role.setOrderNo(null);//序列
		}
		role.setCreater(userId);
		role.setCreatedTime(new Timestamp(new Date().getTime()));
		
		// 调用接口执行更新
		int row = this.roleService.save(role);
		if (row >= 0) {
			attr.addFlashAttribute(ERROR_TITLE, "角色新增成功！");
		} else {
			attr.addFlashAttribute(ERROR_TITLE, "角色新增失败！");
		}
		return REDIRECT_LIST;
	}
	
	/**
	 * 跳转到角色编辑页面
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(HttpServletRequest request, Model model, Role role) {
		
		Role args = new Role();
		args.setRoleId(role.getRoleId());
		// 获取修改的角色信息
		model.addAttribute("role", this.roleService.get(args));
		 
		return "pages/role/role-edit";
	}
	
	/**
	 * 修改角色
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(HttpServletRequest request, Model model, Role role, RedirectAttributes attr) {
		
		//session 获取userId
		Long userId = this.getAccountFromSession().getUserId();
		
		if(role.getOrderNo()!=null && !"".equals(role.getOrderNo())) {
			role.setOrderNo(role.getOrderNo());//序列
		} else {
			role.setOrderNo(null);//序列
		}
		role.setUpdator(userId);
		role.setUpdatedTime(new Timestamp(new Date().getTime()));
		
		// 调用接口执行更新
		int row = this.roleService.update(role);
		
		if (row >= 0) {
			attr.addFlashAttribute(ERROR_TITLE, "角色修改成功！");
		} else {
			attr.addFlashAttribute(ERROR_TITLE, "角色修改失败！");
		}
		return REDIRECT_LIST;
	}
	
	/**
	 * 删除角色
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public void delete(HttpServletRequest request, HttpServletResponse response){

		String roleId = request.getParameter("roleId");
		JSONResult result = new JSONResult();
		
		//删除角色信息
		Role role = new Role();
		role.setRoleId(Long.parseLong(roleId));
		int row = this.roleService.delete(role);
		
		//删除角色菜单信息
		RoleMenu roleMenu = new RoleMenu();
		roleMenu.setRoleId(Long.parseLong(roleId));
		this.roleMenuService.delete(roleMenu);
		
		//删除用户角色信息
		UserRole userRole = new UserRole();
		userRole.setRoleId(Long.parseLong(roleId));
		this.userRoleService.delete(userRole);
		if (row > 0) {
			result.setMessage("删除成功！");
			getPrintWriter(response,JSONArray.toJSONString(result));
		} else {
			result.setStatus(-1);
			result.setMessage("删除失败");
			getPrintWriter(response,JSONArray.toJSONString(result));
		}
	}
	
	/**
	 * 跳转到角色授权页面
	 */
	@RequestMapping(value = "/grantView", method = RequestMethod.GET)
	public String grantView(HttpServletRequest request, Model model, Role role) {
		
		// 获取一级菜单
		Menu menu = new Menu();
		List<Menu> menu1 = this.menuService.getOneList(menu);
		List<Menu> menuNew = new ArrayList<Menu>();
		for(int i=0; i<menu1.size(); i++) {
			menu1.get(i).setLevel(Menu.LEVEL_0);//设置级数 0一级菜单
			menuNew.add(menu1.get(i));
			//获取二级菜单
			menu.setParentId(menu1.get(i).getMenuId());
			List<Menu> menu2 = this.menuService.getTwoList(menu);
			for(int j=0; j<menu2.size(); j++) {
				menu2.get(j).setLevel(Menu.LEVEL_1);//设置级数 1二级菜单
				menuNew.add(menu2.get(j));
				//获取三级菜单
				menu.setParentId(menu2.get(j).getMenuId());
				List<Menu> menu3 = this.menuService.getButtonList(menu);
				for(int k=0; k<menu3.size(); k++) {
					menu3.get(k).setLevel(Menu.LEVEL_2);//设置级数 2三级按钮
					menuNew.add(menu3.get(k));
				}
			}
		}
		model.addAttribute("list", menuNew);
		model.addAttribute("roleId", role.getRoleId());
		 
		return "pages/role/role-grant";
	}
	
	/**
	 * 授权角色菜单
	 */
	@RequestMapping(value = "/grant", method = RequestMethod.POST)
	public String grant(HttpServletRequest request, Role role, RedirectAttributes attr) {
		
		//session 获取userId
		Long userId = this.getAccountFromSession().getUserId();
		
		Map<String, Object> params = new HashMap<String, Object>();
		
		params.put("roleId", request.getParameter("roleId"));//角色Id
		params.put("menuIds", request.getParameter("menuIds"));//菜单组
		params.put("creater", userId.toString());//创建人
		
		// 调用接口执行更新
		roleMenuService.grant(params);
		
		attr.addFlashAttribute(ERROR_TITLE, "授权成功！");
		
		return REDIRECT_LIST;
	}
	
	/**
	 * 获取所有角色（树）
	 */
	@RequestMapping(value = "/findAllTree")
	@ResponseBody
	public List<RoleTree> findAllTree() {
		
		// 获取一级菜单
		Role role = new Role();
		List<Role> role1 = this.roleService.list(role);
		List<RoleTree> roleTree = new ArrayList<RoleTree>();
		for(int i=1; i<role1.size(); i++) {
			RoleTree treeOne = new RoleTree();
			treeOne.setId(role1.get(i).getRoleId());
			treeOne.setText(role1.get(i).getRoleName());
			
			roleTree.add(treeOne);
		}
		return roleTree;
	}
}